<script setup lang="ts">
import { emailLoginApi } from "@/apis/user";
import type { emailLoginForm } from "@/types/login";
import type { FormInstance, FormRules } from "element-plus";
import { md5 } from "js-md5";
import { reactive, ref } from "vue";

const emailFormRef = ref<FormInstance>();
const validatorEmail = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error("请输入邮箱地址"));
  } else {
    if (/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(value)) {
      callback();
    } else {
      callback(new Error("请输入正确的邮箱地址"));
    }
  }
};
const emailFormRules = reactive<FormRules<emailLoginForm>>({
  email: { required: true, validator: validatorEmail, trigger: "blur" },
  password: { required: true, message: "请输入密码", trigger: "blur" },
});
const emailFormData = reactive<emailLoginForm>({
  email: "",
  password: "",
});
const submitLogin = async () => {
  if (emailFormData.email && emailFormData.password) {
    const res = await emailLoginApi({
      email: emailFormData.email,
      password: emailFormData.password,
      md5_password: md5(emailFormData.password),
    });
    console.log(res);
  }
};
const resetForm = () => {
  if (emailFormRef.value) {
    emailFormRef.value.resetFields();
  } else {
    return;
  }
};
</script>
<template>
  <div class="EmailLogin">
    <el-form
      ref="emailFormRef"
      style="max-width: 600px"
      status-icon
      label-width="auto"
      class="demo-ruleForm"
      label-position="top"
      :rules="emailFormRules"
      :model="emailFormData"
    >
      <el-form-item label="邮箱" prop="email">
        <el-input
          type="email"
          autocomplete="off"
          v-model="emailFormData.email"
        />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          type="password"
          autocomplete="off"
          v-model="emailFormData.password"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitLogin"> 登录 </el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<style scoped lang="scss"></style>
